package com.learning.java.optimize.id.generate.redis;

import java.util.Calendar;
import java.util.Date;

import com.learning.java.optimize.id.generate.IIdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName: redisIdServiceImpl
 * Description: 通过redis的Incr实现
 * Date: 2020/3/21 14:38 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
@Service("redisIdServiceImpl")
public class RedisIdServiceImpl implements IIdService {

    @Autowired
    private RedisUtils redis;

    /**
     * 产生订单号
     */
    @Override
    public void createId() {
        // key = 系统名：+ 模块：+ 功能 ：+ key
        String key = "system:order:id";
        String prefix = getPrefix(new Date());
        long id = redis.increment(key, -1);
        // 加工
        System.out.println("insert into order_id(id) values('" + prefix + String.format("%1$05d", id) + "');");
    }

    /**
     * 通过时间生成前缀 - 可根据业务自定定义
     *
     * @param date
     * @return
     */
    //2018-08-01
    private String getPrefix(Date date) {// 18 005 00 0005
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int year = c.get(Calendar.YEAR);
        int day = c.get(Calendar.DAY_OF_YEAR);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        String dayFmt = String.format("%1$03d", day);
        String hourFmt = String.format("%1$02d", hour);
        return (year - 2000) + dayFmt + hourFmt;
    }
}
